<script setup>
import { ref, watch, nextTick, defineExpose } from 'vue'

const { spellingLength } = defineProps(['spellingLength'])
const emit = defineEmits(['update:value'])

// 初始化数组和输入框引用
const inputValues = ref(Array.from({ length: spellingLength }, () => ''))
const inputs = ref([])

// 暴露给父组件的方法
const focusInput = () => {
  const firstEmptyIndex = inputValues.value.findIndex(v => v === '')
  const targetIndex = firstEmptyIndex >= 0 ? firstEmptyIndex : 0
  nextTick(() => {
    if (inputs.value[targetIndex]) {
      inputs.value[targetIndex].focus()
      inputs.value[targetIndex].select()
    }
  })
}

const handleInput = (e, index) => {
  const originalValue = e.target.value
  const filtered = originalValue
    .replace(/[^a-zA-Z]/g, '')
    .toLowerCase()
    .slice(0, 1)

  inputValues.value[index] = filtered
  e.target.value = filtered

  // 自动聚焦下一个输入框
  if (filtered && index < spellingLength - 1) {
    nextTick(() => {
      inputs.value[index + 1]?.focus()
    })
  }
}

const handleBackspace = (e, index) => {
  if (e.target.value === '' && index > 0) {
    e.preventDefault()
    inputValues.value[index - 1] = ''
    nextTick(() => {
      inputs.value[index - 1]?.focus()
      inputs.value[index - 1]?.select()
    })
  }
}

watch(inputValues, (newVal) => {
  emit('update:value', newVal.join(''))
}, { deep: true })

const resetInputs = () => {
  inputValues.value = Array.from({ length: spellingLength }, () => '')
  nextTick(() => focusInput())
}

// 暴露方法给父组件
defineExpose({
  focusInput,
  resetInputs
})
</script>

<template>
  <div class="spelling-box">
    <div v-for="(_, index) in spellingLength" :key="index">
      <input type="text" :value="inputValues[index]" @input="(e) => handleInput(e, index)"
        @keydown.delete="(e) => handleBackspace(e, index)" maxlength="1" :ref="el => inputs[index] = el"
        @keydown.enter="$emit('enter')" />
    </div>
  </div>
</template>
<style scoped lang="scss">
.spelling-box {
  position: relative;
  width: 10vw;
  min-width: 60px;
  height: 10vh;
  min-height: 60px;
  display: flex;
  flex-direction: row;
  gap: 8px;
  padding: 4px;
}

input {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 3VW;
  height: 8vh;
  border: none;
  font-size: 2em;
  text-align: center;
  color: #222222;
  background-color: #ffffff;
  outline: none;
  border-radius: 10px;
  border: #ffcc99 solid 2px;
}
</style>
